import '../../util/_base_export.dart';
import '../../util/_view_export.dart';

import 'package:flutter_stripe_payment/flutter_stripe_payment.dart';
import 'package:url_launcher/url_launcher.dart';

import 'package:pushy_flutter/pushy_flutter.dart';

// import '../../util/app_util.dart';
import '../../blocs/cart.dart';
// import 'screen_msg_main.dart';

class AccountMainScreen extends StatefulWidget {
  AccountMainScreen({Key? key}) : super(key: key);
  _AccountMainScreenState createState() => _AccountMainScreenState();
}

class _AccountMainScreenState extends State<AccountMainScreen> {
  CollectionReference lr_app = FirebaseFirestore.instance.collection('app');

  @override
  void initState() {
    super.initState();
  }

  _login() {
    App.router.navigateTo(context, AppRoutes.loginSignin);
  }

  _cancel() {}

  Future<void> _makePhoneCall(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  _callStripeDialog(BuildContext context) async {
    final _stripePayment = FlutterStripePayment();
    _stripePayment.setStripeSettings(
      App3rdKey.stripe_key,
      App3rdKey.applepay_id,
    );
    var paymentResponse = await _stripePayment.addPaymentMethod();
    switch (paymentResponse.status) {
      case PaymentResponseStatus.succeeded:
        {
          print(paymentResponse.paymentMethodId);
          var lm_result = await AppSession.appUtil.paymentMaintain(paymentResponse.paymentMethodId!);
          if ((lm_result ?? {}).isNotEmpty) {
            // AppSession.stripePayMethodId = paymentResponse.paymentMethodId;
            AppSession.creditcard['pmid'] = paymentResponse.paymentMethodId;
          }
        }
        break;
      case PaymentResponseStatus.failed:
        {
          print(paymentResponse);
        }
        break;
      default:
        {
          print(paymentResponse);
        }
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppColor.greyBg,
      child: SingleChildScrollView(
        child: Column(
          // crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          // crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              child: Stack(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.only(top: 50.h),
                    height: 180.h,
                    // alignment: Alignment.center,

                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/account/profile_bg.png'),
                        fit: BoxFit.cover,
                      ),
                    ),
                    child: Container(
                      alignment: Alignment(0, -1.0),
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      height: 66.h,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Image.asset('assets/account/profile_photo.png'),
                              SizedBox(width: 10.h),
                              Container(
                                height: 66.h,
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                                  children: <Widget>[
                                    Text(((AppSession.authortoken ?? '').isNotEmpty)
                                        ? '已登录'
                                        : '未登录'),
                                    if (AppSession.appUtil.membership.isNotEmpty)
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.start,
                                        crossAxisAlignment: CrossAxisAlignment.center,
                                        children: <Widget>[
                                          Image.asset(
                                              'assets/account/profile_icon_member_small.png'),
                                          Text(' VIP 会员'),
                                        ],
                                      ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                          GestureDetector(
                            onTap: () {
                              if ((AppSession.authortoken ?? '').isEmpty)
                                AppPopupService.showAlertSimple(
                                  'I',
                                  '请先登录',
                                  '',
                                  iv_cancel_text: '先不了',
                                  cancel: _cancel,
                                  iv_confirm_text: '去登录',
                                  confirm: _login,
                                );
                              else {
                                App.router.navigateTo(context, AppRoutes.accountRedeem);
                              }
                            },
                            child: Image.asset('assets/account/profile_btn_coupon.png'),
                          ),
                        ],
                      ),
                    ),
                  ),
                  _memberBlock(),
                  _vipBlock(),
                ],
              ),
            ),
            _addressBlock(),
            _paymentBlock(context),
            _switchAccount(),
            _contactCsBlock(),
            // _termBlock(),
            if ((AppSession.authortoken ?? '').isEmpty) _loginBlock(),
            if ((AppSession.authortoken ?? '').isNotEmpty) _logoutBlock(),
          ],
          // );
          //   },
        ),
      ),
    );
  }

  Widget _vipBlock() {
    return Padding(
      padding: EdgeInsets.only(top: 250.h, bottom: 20.h, left: 16.w, right: 16.w),
      child: Card(
        child: Container(
          height: 160.h,
          width: 343.w,
          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/account/membershipcard_basic.png'),
              fit: BoxFit.cover,
            ),
            borderRadius: BorderRadius.circular(15.0),
          ),
          // padding: EdgeInsets.symmetric(horizontal: 20.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                width: 200.w,
                padding: EdgeInsets.symmetric(vertical: 45.h),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image.asset('assets/account/profile_icon_member.png'),
                        SizedBox(width: 5.w),
                        Text(
                          '土豆商城 VIP',
                          style: TextStyle(color: Colors.white, fontSize: 21.sp),
                        ),
                      ],
                    ),
                    Text('会员每次下单可享受 3 % OFF',
                        style: TextStyle(color: Colors.white, fontSize: 13.sp)),
                  ],
                ),
              ),
              Container(
                width: 110.w,
                child: Center(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      primary: Color(0xFFFF9F05),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(25))),
                    ),
                    child: Text('立即开通'),
                    onPressed: () {
                      AppPopupService.showAlertSimple(
                        'I',
                        'VIP获取方式：上苹果或安卓应用商城给土豆商城五星好评,截图发给客服，即可获取全年3％折扣VIP邀请码',
                        '',
                        // iv_cancel_text: '先不了',
                        // cancel: _cancel,
                        iv_confirm_text: '好的',
                        confirm: _cancel,
                      );
                    },
                  ),
                ),
              ),
              // Align(
              //   alignment: Alignment(1, 0),
              //   child: ((AppSession.appUtil.membership ?? {}).isNotEmpty) ? Text('') : Text(''),
              // ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _memberBlock() {
    return Padding(
      padding: EdgeInsets.only(top: 130.h, left: 30.w, right: 30.w),
      child: Card(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(15.0),
        ),
        child: Container(
          height: 90.h,
          padding: EdgeInsets.symmetric(
            vertical: 14.h,
            horizontal: 24.w,
          ),
          // decoration: BoxDecoration(
          //   borderRadius: BorderRadius.circular(20),
          // ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if ((AppSession.authortoken ?? '').isEmpty)
                    AppPopupService.showAlertSimple(
                      'I',
                      '请先登录',
                      '',
                      iv_cancel_text: '先不了',
                      cancel: _cancel,
                      iv_confirm_text: '去登录',
                      confirm: _login,
                    );
                  else {
                    Pushy?.clearBadge();
                    App.router.navigateTo(context, AppRoutes.accountMsgMain);
                  }
                },
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Image.asset("assets/account/profile_icon_message.png"),
                    Padding(
                      padding: EdgeInsets.only(left: 0.w, right: 0.w),
                      child: Row(
                        children: <Widget>[
                          Text(
                            AppText.text['account_message_name'],
                            style: TextStyle(color: AppColor.greyText, fontSize: 13.sp),
                          ),
                          if ((AppSession.authortoken ?? '').isNotEmpty)
                            FutureBuilder<QuerySnapshot>(
                              future: lr_app
                                  .doc(AppSession.appUtil.data['uid'].toString())
                                  .collection('message')
                                  .where('status', isEqualTo: true)
                                  .get(),
                              builder:
                                  (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                                if (snapshot.hasError) {
                                  return Text("");
                                }

                                if (snapshot.connectionState == ConnectionState.done) {
                                  // Map<String, dynamic> data = snapshot.data.data();
                                  var data = snapshot.data?.docs;
                                  String len = data==null?'0':data.length.toString();
                                  return Text(
                                    len,
                                    style:
                                        TextStyle(color: Colors.red, fontWeight: FontWeight.w600),
                                  );
                                }
                                return Text("");
                              },
                            ),
                          // Text(
                          //   '(' + ')',
                          //   style: TextStyle(color: AppColor.greyText, fontSize: 13.sp),
                          // ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if ((AppSession.authortoken ?? '').isEmpty)
                    AppPopupService.showAlertSimple(
                      'I',
                      '请先登录',
                      '',
                      iv_cancel_text: '先不了',
                      cancel: _cancel,
                      iv_confirm_text: '去登录',
                      confirm: _login,
                    );
                  else {
                    App.router.navigateTo(context, AppRoutes.voucherList);
                  }
                },
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: <Widget>[
                    Image.asset("assets/account/profile_icon_coupon.png"),
                    Padding(
                      padding: EdgeInsets.only(left: 0.w, right: 0.w),
                      child: Row(
                        children: <Widget>[
                          Text(
                            AppText.text['account_voucher_name'],
                            style: TextStyle(color: AppColor.greyText, fontSize: 13.sp),
                          ),
                          // Text(
                          //   '(' + ')',
                          //   style: TextStyle(color: AppColor.greyText, fontSize: 13.sp),
                          // ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _addressBlock() {
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          if ((AppSession.authortoken ?? '').isEmpty)
            AppPopupService.showAlertSimple(
              'I',
              '请先登录',
              '',
              iv_cancel_text: '先不了',
              cancel: _cancel,
              iv_confirm_text: '去登录',
              confirm: _login,
            );
          else {
            App.router.navigateTo(context, AppRoutes.accountAddrList);
          }
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.clipboard_account,
                    LineIcons.userAlt,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '地址信息',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.plus,
                    LineIcons.plus,
                    color: AppColor.yellowText,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 5.w, right: 10.w),
                    child: Text(
                      '更新',
                      style: TextStyle(color: AppColor.yellowText, fontSize: 13.sp),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _switchAccount() {
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          if ((AppSession.authortoken ?? '').isEmpty)
            AppPopupService.showAlertSimple(
              'I',
              '请先登录',
              '',
              iv_cancel_text: '先不了',
              cancel: _cancel,
              iv_confirm_text: '去登录',
              confirm: _login,
            );
          else {
            App.router.navigateTo(context, AppRoutes.accountSwitch);
          }
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.credit_card_multiple,
                    Icons.credit_card,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '切换账户',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      (AppSession.wholesale_wh_id == 0) ? '当前为普通账户' : '当前为团购批发账户',
                      style: TextStyle(color: AppColor.greyText, fontSize: 12.sp),
                    ),
                  ),
                ],
              ),
              Icon(
                Icons.chevron_right,
                color: AppColor.blackMain,
                size: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _paymentBlock(BuildContext context) {
    var lv_str_credit = '';

    if (AppSession.creditcard.isNotEmpty) {
      if ((AppSession.creditcard['last4'] ?? '').isNotEmpty) {
        print(AppSession.creditcard);
        lv_str_credit = '已添加';
      }
    }
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          _callStripeDialog(context);
          // if ((AppSession.authortoken ?? '').isEmpty)
          //   AppPopupService.showAlertSimple(
          //     'I',
          //     '请先登录',
          //     '',
          //     iv_cancel_text: '先不了',
          //     cancel: _cancel,
          //     iv_confirm_text: '去登录',
          //     confirm: _login,
          //   );
          // else {
          //   _callStripeDialog(context);
          // }
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.credit_card_multiple,
                    Icons.credit_card,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '支付管理',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      lv_str_credit,
                      style: TextStyle(color: AppColor.greyText, fontSize: 12.sp),
                    ),
                  ),
                ],
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.plus,
                    LineIcons.plus,
                    color: AppColor.yellowText,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 5.w, right: 10.w),
                    child: Text(
                      '更新',
                      style: TextStyle(color: AppColor.yellowText, fontSize: 13.sp),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _contactCsBlock() {
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          // _makePhoneCall('tel:${AppUtil.cs_cell}'); //AppUtil.cs_cell
          var lv_uid = '';
          print(lv_uid);
          if (AppSession.appUtil.data.isNotEmpty) {
            if (AppSession.appUtil.data['uid'] !=null) {
              lv_uid = AppSession.appUtil.data['uid'].toString();
              Intercom.registerIdentifiedUser(userId: lv_uid);
            } else {
              Intercom.registerUnidentifiedUser();
            }
          }


          // Intercom.registerIdentifiedUser(userId: lv_uid);
          await Intercom.displayMessenger();
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.face_agent,
                    LineIcons.userAlt,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '联系客服',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                ],
              ),
              Icon(
                Icons.chevron_right,
                color: AppColor.blackMain,
                size: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _termBlock() {
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          // final flutterWebViewPlugin = new FlutterWebviewPlugin();
          // flutterWebViewPlugin.close();
          // var encodedUrl = Uri.encodeComponent(AppConst.term_url);
          // App.router.navigateTo(context, '/webview/${encodedUrl}');
          App.router.navigateTo(context, AppRoutes.accountMsgMain);
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.signature_text,
                    LineIcons.sign,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      'Privacy Policy & Terms Conditions',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                ],
              ),
              Icon(
                Icons.chevron_right,
                color: AppColor.blackMain,
                size: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _loginBlock() {
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          App.router.navigateTo(context, AppRoutes.loginSignin);
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // Icons.login_variant,
                    Icons.clear,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '登录',
                      style: TextStyle(color: AppColor.yellowText, fontSize: 15.sp),
                    ),
                  ),
                ],
              ),
              Icon(
                Icons.chevron_right,
                color: AppColor.yellowText,
                size: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _logoutBlock() {
    return Card(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          final FirebaseAuth _auth = FirebaseAuth.instance;
          await _auth.signOut();
          AppSession.bottomIndex = 0;
          AppSession.clearSession();

          Provider.of<CartBloc>(context, listen: false)..clear();

          await AppSession.appUtil.clear();
          Navigator.pushNamedAndRemoveUntil(context, '/', (_) => false);
        },
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.logout_variant,
                    LineIcons.rssSquare,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '退出',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                ],
              ),
              Icon(
                Icons.chevron_right,
                color: AppColor.blackMain,
                size: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _contactUsBlock() {
    return Card(
      child: GestureDetector(
        onTap: () async {},
        child: Container(
          height: 80.h,
          padding: EdgeInsets.symmetric(
            vertical: 24.h,
            horizontal: 24.w,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: <Widget>[
                  Icon(
                    // MaterialCommunityIcons.clipboard_check_outline,
                    LineIcons.bookOpen,
                    color: AppColor.yellowText,
                    size: 26,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, right: 0.w),
                    child: Text(
                      '留言板',
                      style: TextStyle(color: AppColor.blackMain, fontSize: 15.sp),
                    ),
                  ),
                ],
              ),
              Icon(
                Icons.chevron_right,
                color: AppColor.blackMain,
                size: 30,
              ),
            ],
          ),
        ),
      ),
    );
  }
}
